package net.paoding.rose.jade.statement.jexl.analysis.impl;

import net.paoding.rose.jade.statement.jexl.Jexl3Execute;
import net.paoding.rose.jade.statement.jexl.analysis.Analysis;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * if 表达式解析
 * @author fusheng.zhang
 * @date 2022-03-05 16:24:15
 */
public class IfElseAnalysis implements Analysis {

    /**
     * if条件语句 () 条件表达式
     */
    private List<Analysis> ifConditions;
    /**
     * {} 执行语句
     */
    private List<Analysis> ifExecutes;
    /**
     * else {} 执行语句
     */
    private List<Analysis> elseExecutes;

    @Override
    public String toString() {
        if (Objects.isNull(ifConditions)) return "";
        StringBuilder str = new StringBuilder();
        str.append("if(");
        ifConditions.forEach(analysis -> str.append(analysis.toString()));
        str.append(")").append("{");
        if (Objects.nonNull(ifExecutes)) {
            ifExecutes.forEach(analysis -> str.append(analysis.toString()));
        }
        str.append("}");
        if (Objects.nonNull(elseExecutes)) {
            str.append(" else {");
            elseExecutes.forEach(analysis -> str.append(analysis.toString()));
            str.append("}");
        }
        return str.toString();
    }

    @Override
    public void execute(Jexl3Execute jexl3Execute) {
        String scriptText = toStr(ifConditions.stream().map(Analysis::toString).collect(Collectors.joining()));
        Object o = jexl3Execute.execute(jexl3Execute.getParams(), jexl3Execute.getConstantParams(), scriptText);
        if (Objects.nonNull(o) && Boolean.parseBoolean(o.toString())) {
            if (!CollectionUtils.isEmpty(ifExecutes)) {
                ifExecutes.forEach(analysis -> analysis.execute(jexl3Execute));
            }
        } else {
            if (!CollectionUtils.isEmpty(elseExecutes)) {
                elseExecutes.forEach(analysis -> analysis.execute(jexl3Execute));
            }
        }
    }

    public List<Analysis> getIfConditions() {
        return ifConditions;
    }

    public void setIfConditions(List<Analysis> ifConditions) {
        this.ifConditions = ifConditions;
    }

    public List<Analysis> getIfExecutes() {
        return ifExecutes;
    }

    public void setIfExecutes(List<Analysis> ifExecutes) {
        this.ifExecutes = ifExecutes;
    }

    public List<Analysis> getElseExecutes() {
        return elseExecutes;
    }

    public void setElseExecutes(List<Analysis> elseExecutes) {
        this.elseExecutes = elseExecutes;
    }
}

